package com.starbaba.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.struts2.ServletActionContext;

import com.jumai.server.qiniu.QiniuUploadUtils;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.starbaba.core.utils.Base64Utils;

@SuppressWarnings("all")
public class ImgUploadUtil {
	
	public static String updateImgByteData2Qiniu(String data) {
		String uploadedUrl = null;
		try {
			String dstPath = ServletActionContext.getServletContext().getRealPath("/uploadimg");
			File out = new File(dstPath);
			if(!out.exists()){
				out.mkdirs();
			}
			String tmpFilePath = dstPath + "/" + System.currentTimeMillis() + ".png";
			File tmpTargetFile = new File(tmpFilePath);
			if (tmpTargetFile.exists()) {
				tmpTargetFile.delete();
			}
			saveImgFromBase64(data, tmpTargetFile);
//			uploadedUrl = QiniuService.uploadImg2Qiniu(tmpFilePath, "image");
			FileInputStream in = new FileInputStream(tmpFilePath);
			// Zone为七牛机房所在地，根据源所在机房配置
	        Configuration config = new Configuration(Zone.zone0()); 
	        uploadedUrl = QiniuUploadUtils.updateImg("image", in, null, config);
	        in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return uploadedUrl;
	}
	
	
	public static void saveImgFromBase64(String data, File file) {
		String imgdata = data.substring(data.indexOf(",") + 1);
        byte[] buf = Base64Utils.getFromBASE64(imgdata);
        FileOutputStream  out = null;
        try {
			out = new FileOutputStream(file);
			out.write(buf);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally
		{
			if(out != null)
			{
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		String data = "";
		String imgdata = data.substring(data.indexOf(",") + 1);
        
//        saveImgFromBase64(imgdata , new File("D:\\UtilityRoom\\111.jpg"));
        
        updateImgByteData2Qiniu(imgdata);
//        byte[] buf = Base64Utils.getFromBASE64(imgdata);
//        
//        try {
//			FileOutputStream  out = new FileOutputStream(new File("D:\\UtilityRoom\\111.jpg"));
//			out.write(buf);
//			out.close();
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

}
